import React, { Component } from 'react'
import './index.css'
import Header from '../../components/ToDoList/Header'
import Footer from '../../components/ToDoList/Footer'
import List from '../../components/ToDoList/List'

export default class ToDoList extends Component {
  state = {
    todos: []
  }
  changeDone = (changeItemId) => {
    let {todos} = this.state
    const index = todos.findIndex(item => item.id === changeItemId)
    todos[index].done = !todos[index].done
    this.setState({todos: todos})
  }
  checkAll = (checked) => {
    const {todos} = this.state
    const res = todos.map(item => {
      item['done'] = checked
      return item
    })
    console.log(res);
    this.setState({todos: res})
  }
  addToDo = (name) => {
    const {todos} = this.state
    const todo = {
      id: todos.length+1,
      name,
      done: false
    }
    this.setState({todos: [todo, ...todos]})
  }
  clearCompleteItem = () => {
    const {todos} = this.state
    const flag = window.confirm('确定要清除所有任务吗？')
    if (flag) {
      this.setState({
        todos: todos.filter(item => item.done === false)})
      }
    }

  deleteItem = (id) => {
    let {todos} = this.state
    todos = todos.filter(item => item.id !== id)
    const flag = window.confirm('确定要删除吗？')
    if (flag) {
      this.setState({todos: todos})
    }
  }
  render() {
    const {todos} = this.state
    return (
      <div>
        <div className="todo-container">
          <div className="todo-wrap">
            <Header onAddToDo={this.addToDo} todos={todos}/>
            <List deleteItem={this.deleteItem} changeDone={this.changeDone} todos={todos}/>
            <Footer checkAll={this.checkAll} todos={todos} clearCompleteItem={this.clearCompleteItem}/>
          </div>
        </div>
      </div>
    )
  }
}
